首页 > 试题广场 >

旋转链表

[编程题]旋转链表
  • 热度指数:3945 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定链表的头节点,旋转链表,将链表每个节点往右移动 k 个位置,原链表后 k 个位置的节点则依次移动到链表头。

即,例如链表 : 1->2->3->4->5 k=2 则返回链表 4->5->1->2->3

数据范围:链表中节点数满足
示例1

输入

{1,2,3,4,5},2

输出

{4,5,1,2,3}
示例2

输入

{1,2,3},3

输出

{1,2,3}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
class Solution:
    def rotateLinkedList(self , head: ListNode, k: int) -> ListNode:
        if head == None:
            return head
        rare = head
        length = 1
        while rare.next != None:
            rare = rare.next
            length = length + 1 
        rare.next = head
        step = length - k % length
        while step > 1:
            head = head.next
            step = step - 1
        p = head
        head = head.next
        p.next = None
        return head

发表于 2024-05-06 21:17:06 回复(0)
class Solution:
    def rotateLinkedList(self , head: ListNode, k: int) -> ListNode:
        # write code here
        if not head:
            return None
        length = 0
        temp = head
        while temp.next:
            length += 1
            temp = temp.next
        temp.next = head
        k = k % (length+1)
        temp = head
        for _ in range(length-k):
            temp = temp.next
        head = temp.next
        temp.next = None
        return head

发表于 2022-07-24 22:56:46 回复(0)

问题信息

难度:
2条回答 1653浏览

热门推荐

通过挑战的用户

查看代码